import React from 'react';
import { Tabs, Echarts } from 'weaver-mobile';
import * as API_HOMEPAGE from '../../../../apis/homepage';
import Loading from '../../Loading';

import { getEChartsOption } from './options';

class Chart extends React.Component {
  constructor(props) {
    super(props);
    this.onLoadData = this.onLoadData.bind(this);
    this.state = {
      loading: false,
      tabs: [],
      tab: {},
      result: {}
    };
  }

  componentWillMount() {
    const { tabs } = this.props;
    if (tabs && tabs.length) {
      const tab = tabs[0];
      this.setState({ tabs });
      this.onLoadData(tab);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.refreshing) {
      const { tabs } = nextProps;
      if (tabs && tabs.length) {
        const tab = tabs[0];
        this.setState({ tabs });
        this.onLoadData(tab);
      }
    }
  }

  render() {
    const { loading, tabs = [], tab = {}, result = {} } = this.state;
    const { data } = result;

    let tabsCom = null;
    if (tabs && tabs.length > 1) {
      let page = 0;
      for (let i = 0, len = tabs.length; i < len; i++) {
        if (tabs[i].tabid == tab.tabid) {
          page = i;
          break;
        }
      }
      tabsCom = <Tabs tabs={tabs} page={page} renderTabBar={props => <Tabs.ExpandTabBar {...props} fix={8} />} onTabClick={item => this.onLoadData(item)} />;
    }

    let dataCom = null;
    if (!loading && data && (data.series || data.data)) {
      dataCom = (
        <div className="data-ul">
          <div style={{ width: '100%', height: '200px' }}>
            <Echarts option={getEChartsOption(data)} />
          </div>
        </div>
      );
    }

    return (
      <div className="content">
        {tabsCom}
        <div className="data">{dataCom}</div>
      </div>
    );
  }

  onLoadData(tab) {
    const { hpid, subCompanyId, eid, ebaseid } = this.props;
    const { tabid } = tab;
    const params = { hpid, subCompanyId, eid, ebaseid, tabid, tabId: tabid };

    this.setState({ loading: true, tab });
    API_HOMEPAGE.getElementData(params).then(result => {
      const { data } = result;
      this.setState({ loading: false, result: { data } });
    });
  }
}

export default Chart;
